package com.small.service;

import com.small.main.DealMain;
import com.small.utils.*;
import com.sun.org.apache.bcel.internal.generic.NEW;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.CharBuffer;
import java.util.*;
import java.util.logging.Logger;
import java.util.stream.Collectors;

/**
 * @author syd
 * @create 2020-12-12 12:44
 */
public class DealMethod {

    private static Logger log = Logger.getGlobal();

    //0.获取输入与输出目录
    public String getPath(String type) throws IOException {
        log.info(log.toString());

        Properties prop = new Properties();
        PropertiesUtil propertiesUtil = new PropertiesUtil();
        propertiesUtil.getProperties(prop);

        if ("in".equals(type)) {
            return prop.getProperty("deal.in");
        } else {
            return prop.getProperty("deal.out");
        }
    }

    //1.处理文件
    public List<Map<String, String>> dealFile(File fe) throws Exception {

        InputStream in = null;
        String version;
        ExcelUtil excel;
        List<List<String>> read;

        try {
            log.info("开始读取文件：" + fe.getName() + "...");

            //判断版本
            version = ExcelUtil.isExcel2003(fe.getName()) ? "2003" : "2007";
            in = new FileInputStream(fe);
            excel = new ExcelUtil(in, version);

            log.info("抽取sheet的标题索引" + "...");
            //获取需要抽取列的键值
            Map<Integer, String> titleMap = getTitleIndex(excel);
           // System.out.println("map" + titleMap.toString());

            log.info("整理结果集...");
            //获取结果集数据
            List<Map<String, String>> dataMap = getDataMap(titleMap, excel);

            //int size=dataMap.size();
            //System.out.println("size = " + size);
            /*for (Map<String, String> smap : dataMap) {
                System.out.println(smap.toString()+".");
            }*/

            log.info(fe.getName()+"=>结果集条数："+dataMap.size()+"条");

            return dataMap;

        } catch (Exception e) {
            e.printStackTrace();
            return null;
        } finally {
            if (in != null) {
                in.close();
            }
        }
    }

    /**
     * 整理最终结果集
     *
     * @param titleMap
     * @param excelUtil
     * @return
     * @throws Exception
     */

    private List<Map<String, String>> getDataMap(Map<Integer, String> titleMap, ExcelUtil excelUtil) throws Exception {

        //获取sheet页数据
        List<Map<Integer, String>> maps = excelUtil.readMap(0);
        List<Map<Integer, String>> nmaps = new ArrayList<>();
        Set<Integer> keyTitleSet = titleMap.keySet();
        //定义分割符
        CharBuffer charBuffer = CharBuffer.allocate(6);
        charBuffer.append(",").append(";").append("，").append("；").append(" ").append("、");

        //遍历提取数据
        maps.forEach(i -> {
            Set<Integer> keySet = i.keySet();
            Map<Integer, String> nmap = new HashMap<>();
            keySet.forEach(k -> {
                if (keyTitleSet.contains(k)) {
                    nmap.put(k, i.get(k));
                }
            });
            nmaps.add(nmap);
        });

        //整理数据
        List<Map<String, String>> r_maps = new ArrayList<>();
        nmaps.forEach(
                i -> {
                    Set<Integer> keySet = i.keySet();
                    Map<String, String> nmap = new HashMap<>();
                    String phones = "";
                    String name1 = "";
                    String name2="";
                    String name="";

                    for (Integer sd : keySet) {
                        for (Integer st : keyTitleSet) {
                            //整理联系方式
                            if (titleMap.get(st).contains("电话") && sd.equals(st)) {
                                phones += phones.length() == 0 ? i.get(sd).trim() : "," + i.get(sd).trim();

                                if (!phones.isEmpty() && phones.contains(charBuffer)) {
                                    String regex = "[,;、，；\\s]";
                                    phones = Arrays.stream(phones.split(regex)).distinct().collect(Collectors.toList()).toString();

                                }
                            }
                            //整理客户名称，先取法定代表人，法定代表人取不到再取公司名称
                            if (titleMap.get(st).contains("名称") && sd.equals(st)) {
                                name1 = i.get(sd).trim();
                            }

                            if (titleMap.get(st).contains("代表人") && sd.equals(st)) {
                                if(!i.get(sd).trim().isEmpty()){
                                    name2 = i.get(sd).trim();
                                }
                            }
                        }
                        //去掉[]号
                        if (phones.startsWith("[") && phones.endsWith("]")) {
                            phones = phones.substring(1, phones.length() - 1).trim().replace(" ", "");
                            phones=phones.replace(",","、");
                        }
                        //去掉-号
                        if (phones.contains("-")||phones.contains("、、")) {
                            phones = phones.replace("、-", "").replace("、、","、");
                            //System.out.println(phones);
                        }

                        //取name值
                        if(!"".equals(name2)){
                            name=name2;
                        }else{
                            name=name1;
                        }

                        if(!name.isEmpty()){
                            nmap.put(name,phones);
                        }

                        if (!"".equals(name1) && !"".equals(name2)) {
                            nmap.remove(name1);
                        }
                    }
                    r_maps.add(nmap);
                }
        );
        charBuffer.clear();
        return r_maps;
    }

    /**
     * 获取标题行集合,提取客户名称与电话的相关键值
     *
     * @param excelUtil
     * @return
     * @throws Exception
     */
    private Map<Integer, String> getTitleIndex(ExcelUtil excelUtil) throws Exception {

        Map<Integer, String> map = new HashMap<>();
        Map<Integer, String> kv = excelUtil.getRowKeyValue(0, 1);

        if (kv.isEmpty()) {
            log.warning("文件格式有问题，请核查文件格式！");
            return null;
        }

        Set<Integer> keySet = kv.keySet();
        //System.out.println("keySet = " + keySet.toString());
        keySet.forEach(k -> {
            //System.out.println(k+","+kv.get(k)+","+kv.get(k).indexOf("企业名称"));
            if (kv.get(k).indexOf("公司名称") > -1 || kv.get(k).indexOf("企业名称") > -1 || kv.get(k).indexOf("法定代表人") > -1 || kv.get(k).indexOf("电话") > -1) {
                map.put(k, kv.get(k));
            }
        });

        return map;
    }

    public boolean exportCsv(List<Map<String, String>> maps,String name) throws Exception {

        CsvUtil csvUtil = new CsvUtil();

        //生成文件名
        String nname = name.substring(0, name.lastIndexOf("."));
        String fileName=this.getPath("out")+"\\"+nname+".csv";

        //生成文件标题列
        //List<String[]> list=new ArrayList<>();
        int length = 0;
        int max = 0;
        for (Map<String, String> map : maps) {
            Set<String> keySet = map.keySet();
            for (String s : keySet) {
                String[] s1 = map.get(s).split("、");
               // System.out.println("s1.length = " + s1.length);
                length=s1.length>max?s1.length:max;
                max=length;
                //list.add(s1);
            }
        }

        //String s = list.stream().max((o1, o2) -> (o1.length()).compareTo(o2.length())).get();


        String[] headers = new String[max+1];
        headers[0]="客户名称";

        for (int i = 1; i < max+1; i++) {
            headers[i]="联系方式";
        }

        //根据标题列处理map
        List<LinkedHashMap<Integer,String>> rlist = new ArrayList<>();

        for (Map<String, String> map : maps) {
            LinkedHashMap<Integer,String> rmap=new LinkedHashMap<>();
            Set<String> keySet = map.keySet();
            String s2="";
            String s3="";
            for (String s1 : keySet) {
                s2 = map.get(s1).length()>0?map.get(s1):s2;
                s3=s1;
            }
            String[] split = s2.split("、");
            //System.out.println("split = " + s2.toString());

            for (int i = 0; i < max + 1; i++) {
                if(i==0){
                   rmap.put(i,s3);
                }
                if(i>0 && split.length>=i){
                    //System.out.println(i);
                    //System.out.println(split[0]);
                    rmap.put(i,split[i-1].trim());
                }else if(i>0){
                     rmap.put(i,"");
                }
            }
           // System.out.println(rmap.toString());
            rlist.add(rmap);
        }

        boolean b = csvUtil.toWrite(fileName,headers,rlist);
        if(b){
            log.info("文件输出完成！"+name);
        }

        return true;
    }

    public static void main(String[] args) {

      String s="0311-68036805 15511112608";
        CharBuffer charBuffer = CharBuffer.allocate(5);
        charBuffer.append(",").append(";").append("，").append("；").append(" ");

        boolean contains = s.contains(charBuffer);
        System.out.println("contains = " + contains);

        String regex="[,;、，；\\s]";
        String[] split = s.split(regex);

        for (String s1 : split) {
            System.out.println("s1 = " + s1);
        }
    }
}